//
//  DHOrderController.m
//  精品酒店
//
//  Created by DIANGHONG on 2018/5/7.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "DHOrderController.h"
#import "DHNavbarView.h"
#import "DHOrderButton.h"
#import "DHOrderCell.h"
#import <CoreLocation/CoreLocation.h>
NSString *orderCellID = @"orderCellID";
@interface DHOrderController ()<UITableViewDataSource, UITableViewDelegate, DHOrderCellDelegate,CLLocationManagerDelegate>
@property(nonatomic ,strong)DHNavbarView *navbar; // 导航栏

@property(nonatomic ,strong)UIView *filterView; // 筛选View

@property(nonatomic ,strong)DHOrderButton *currentBtn;

@property(nonatomic ,strong)DHOrderListViewModel *viewModel;

@property (nonatomic,strong ) CLLocationManager *locationManager;//定位服务
@property (nonatomic,copy) NSString *currentCity;   //城市
@property (nonatomic,copy) NSString *strLatitude;   //经度
@property (nonatomic,copy) NSString *strLongitude;  //维度
@property(nonatomic ,assign)int page;

@property(nonatomic ,strong)NSDictionary *params; // 记录筛选界面筛选的参数
@end
@implementation DHOrderController

- (DHOrderListViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[DHOrderListViewModel alloc] init];
    }
    return _viewModel;
}
- (void)locatemap{
    
    if ([CLLocationManager locationServicesEnabled]) {
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        [_locationManager requestAlwaysAuthorization];
        _currentCity = [[NSString alloc]init];
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 5.0;
        [_locationManager startUpdatingLocation];
    }
}
#pragma mark: - UITabBarControllerDelegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    DHBaseController *vc = viewController.childViewControllers.firstObject;

    if ([vc isMemberOfClass:[DHServiceController class]]) {
        // 判断手机是否安装QQ
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web",DHNetworkManager.shareManager.qq]];
        if([[UIApplication sharedApplication] canOpenURL:url]){
            [[UIApplication sharedApplication] openURL:url];
            
        } else {
            UIAlertView*ale=[[UIAlertView alloc] initWithTitle:@"提示" message:@"您没有安装手机QQ，请安装手机QQ后重试，或用PC进行操作。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            ale.delegate = self;
            [ale show];
            
        }
        return NO;
    }
    // NSLog(@"%@---%@",viewController.childViewControllers.firstObject,[self class]);
    
    return YES;

}

// 重写父类方法
- (void)shouldLogWeb
{
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = true;
    
}

// lazy navbar
- (DHNavbarView *)navbar{
    if (!_navbar)
    {
        CGRect frame;
         frame = KIsiPhoneX ? CGRectMake(0, 0, kScreenWidth, 88) : CGRectMake(0, 0, kScreenWidth, 64);
        _navbar = [DHNavbarView navbarViewWithFrame:frame title:@"全部任务" isHiddenReturn:YES];
    }
    return _navbar;
}
// lazy filterView
- (UIView *)filterView
{
    if (!_filterView){
        _filterView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.navbar.frame), kScreenWidth, 44)];
        _filterView.backgroundColor = UIColor.whiteColor;
        DHOrderButton *orderBtn = [DHOrderButton orderButtonWithFrame:CGRectMake(0, 0, kScreenWidth / 2, _filterView.bounds.size.height) title:@"任务"];
       // [orderBtn addTarget:self action:@selector(taskButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        orderBtn.selected = YES;
        
        DHOrderButton *orderBtn1 = [DHOrderButton orderButtonWithFrame:CGRectMake(CGRectGetMaxX(orderBtn.frame), 0, kScreenWidth / 2, _filterView.bounds.size.height) title:@"筛选"];
        [orderBtn1 addTarget:self action:@selector(filterButtonClick) forControlEvents:UIControlEventTouchUpInside];

        
        [_filterView addSubview:orderBtn];
        [_filterView addSubview:orderBtn1];

    }
    return _filterView;
}
#pragma mark - 定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication]openURL:settingURL];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancel];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 定位成功
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    [_locationManager stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //当前的经纬度
    NSLog(@"当前的经纬度 %f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
    
    self.strLongitude = [NSString stringWithFormat:@"%f",currentLocation.coordinate.longitude];
    self.strLatitude =  [NSString stringWithFormat:@"%f",currentLocation.coordinate.latitude];;
    //这里的代码是为了判断didUpdateLocations调用了几次 有可能会出现多次调用 为了避免不必要的麻烦 在这里加个if判断 如果大于1.0就return
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //地理反编码 可以根据坐标(经纬度)确定位置信息(街道 门牌等)
        [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (placemarks.count >0) {
                CLPlacemark *placeMark = placemarks[0];
                self->_currentCity = placeMark.locality;
                if (!self->_currentCity) {
                    self->_currentCity = @"无法定位当前城市";
                }
                //看需求定义一个全局变量来接收赋值
                //            NSLog(@"当前国家 - %@",placeMark.country);//当前国家
                NSLog(@"当前城市 - %@",self->_currentCity);//当前城市
                //self.leftNavButton.titleLabel.text = self->_currentCity;
                //[self.addrBtn setTitle:self->_currentCity forState:UIControlStateNormal];
                //            NSLog(@"当前位置 - %@",placeMark.subLocality);//当前位置
                //            NSLog(@"当前街道 - %@",placeMark.thoroughfare);//当前街道
                //            NSLog(@"具体地址 - %@",placeMark.name);//具体地址
                NSString *message = [NSString stringWithFormat:@"%@,%@,%@,%@,%@",placeMark.country,self->_currentCity,placeMark.subLocality,placeMark.thoroughfare,placeMark.name];
                
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"好", nil];
                //            [alert show];
            }else if (error == nil && placemarks.count){
                
                NSLog(@"NO location and error return");
            }else if (error){
                
                NSLog(@"loction error:%@",error);
            }
        }];
    });
    //[self loadHomeTaskListWithPullUP:NO];
}

#pragma mark: - 筛选按钮监听
- (void)filterButtonClick
{
    
    // 创建筛选控制器
    DHFilterViewController *filterVC = [[DHFilterViewController alloc] init];
    __weak typeof(filterVC) WeakVC = filterVC;
    filterVC.filterButtonClick = ^(NSDictionary *params)
    {
        self.params = params;
        self.viewModel = nil;
        [self.tableView reloadData];
        [WeakVC dismissViewControllerAnimated:true completion:nil];
    };
    filterVC.clearAreaList = self.viewModel.clearAreaList;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:filterVC];
    CWLateralSlideConfiguration *cw = [CWLateralSlideConfiguration configurationWithDistance:0 maskAlpha:0.4 scaleY:0.8 direction:CWDrawerTransitionFromRight backImage:nil];
    [self cw_showDrawerViewController:nav animationType:1 configuration:cw];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}

- (void)setupUI
{
    [self setThisViewUI];
    [self loadDataWithPullup:NO];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHOrderCell" bundle:nil] forCellReuseIdentifier:orderCellID];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadDataWithPullup:NO];
    }];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadDataWithPullup:YES];
    }];
    self.tableView.mj_footer = footer;
    self.tableView.mj_header = header;
    self.page = 1;
    
}

- (void)loadDataWithPullup:(BOOL)pullup{
    [self.viewModel loadClearAreaListWithKey:DHNetworkManager.shareManager.userAccount.key FiniedBlock:^(BOOL isSuccess)
     {
         if (!isSuccess)
         {
             [SVProgressHUD showErrorWithStatus:@"网络有问题"];
             return ;
         }
         
         
     }];

    [self.viewModel loadOrderStatusListWithPullup:pullup page:self.page lng:self.strLongitude lat:self.strLatitude area_name:nil params:self.params FiniedBlock:^(BOOL isSuccess,BOOL shouldRefreshed) {
      
        
        if (!isSuccess && !shouldRefreshed) {
            [SVProgressHUD showErrorWithStatus:@"网络有问题"];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            return ;
        }
        if (isSuccess && !shouldRefreshed) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
 
        
        if (isSuccess && shouldRefreshed) {
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
    }];
}

- (void)setThisViewUI
{
    self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.filterView.frame), kScreenWidth, kScreenHeight - self.tabBarController.tabBar.bounds.size.height);
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [self setupNav];
    [self.view addSubview:self.filterView];
    //self.view.backgroundColor = [UIColor colorWithRed:245.0f/255.0f green:245.0f/255.0f  blue:245.0f/255.0f  alpha:1.0f];
    self.tableView.rowHeight = 120;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 48, 0);
}
#pragma mark: - 设置导航栏
- (void)setupNav
{
    self.navigationController.navigationBar.hidden = true;
    [self.view addSubview:self.navbar];
}
#pragma mark: - UITableViewDelegate UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.viewModel.listModel.list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DHOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:orderCellID forIndexPath:indexPath];
    
    cell.orderModel = self.viewModel.listModel.list[indexPath.row];
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{
    DHOrderDetailController *detailVC = [[DHOrderDetailController alloc] init];
    detailVC.hidesBottomBarWhenPushed = true;
    
    NSString *strLongitude = self.strLongitude ? self.strLongitude : @"0";
    NSString *strLatitude = self.strLatitude ? self.strLatitude : @"0";

    //@{@"id":self.viewModel.listModel.list[indexPath.row].ID,@"lng":strLongitude,@"lat":strLatitude}
    NSMutableDictionary *requestInfo = [NSMutableDictionary dictionary];
    requestInfo[@"id"] = self.viewModel.listModel.list[indexPath.row].ID;
    requestInfo[@"lng"] = strLongitude;
    requestInfo[@"lat"] = strLatitude;
    requestInfo[@"key"] = DHNetworkManager.shareManager.userAccount.key;
    requestInfo[@"store_id"] = self.viewModel.listModel.list[indexPath.row].store_id;
    detailVC.requestInfo = requestInfo;
    
    [self.navigationController pushViewController:detailVC animated:true];
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}

- (void)orderCellSelectedOrderButtonClick:(DHOrderCell *)cell
{
    if (!DHNetworkManager.shareManager.userAccount.is_auth.boolValue)
    {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"key"] = DHNetworkManager.shareManager.userAccount.key;
        param[@"id"] = cell.orderModel.ID;
        param[@"store_id"] = cell.orderModel.store_id;
        
        [DHNetworkManager.shareManager postTaskWithParam:param completion:^(BOOL isSuccess, NSString *statusInfo)
         {
             if (!isSuccess) {
                 [SVProgressHUD showErrorWithStatus:statusInfo];
                 return ;
             }
             [SVProgressHUD showSuccessWithStatus:statusInfo];
         }];
    }else{
        NSLog(@"弹窗");
        DHTipsView *tipView = [DHTipsView tipViewWithFrame:CGRectMake(0, 0, kScreenWidth - 24, 110)];
        STModal *modal = [STModal modal];
        modal.hideWhenTouchOutside = true;
        [modal showContentView:tipView animated:YES];
        
        tipView.completUserInfoClick =
        ^{
            [modal hide:true];
            DHUserInfoController *userInfoVC = [DHUserInfoController userInfo];
            userInfoVC.hidesBottomBarWhenPushed = true;
            [self.navigationController pushViewController:userInfoVC animated:true];
        };
    }
}
@end
